/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals Application, settings, NMRSpectrum, MessageBox, Dialog, GroupBox, ComboBox, qsTr, MnUi*/
/*jslint plusplus: true, indent: 4*/

function setSolvent() {
	"use strict";

	function currentDocumentSelection() {
		var selItems = [],
			selPages = Application.mainWindow.activeWindow().selectedPages(),
			p,
			i,
			page;

		if (selPages && selPages.length > 0) {
			for (p = 0; p < selPages.length; ++p) {
				for (i = 0; i < selPages[p].itemCount(); ++i) {
					selItems.push(selPages[p].item(i));
				}
			}
		} else {
			selItems = Application.mainWindow.activeWindow().selection();
		}

		if (selItems.length <= 0) {
			page = Application.mainWindow.activeWindow().curPage();
			for (i = 0; i < page.itemCount(); ++i) {
				selItems.push(page.item(i));
			}
		}

		return selItems;
	}

	var solvents = ["DMSO", "Chloroform", "Water", "DMF", "Ethanol", "Methanol", "Benzene",
					"Acetone", "Acetic Acid", "Acetonitrile", "Dioxane", "Methylene Chloride",
					"Pyridine", "THF", "Toluene", "Cyclohexane", "Diethylether", "Dimethylacetamide",
					"Ethylacetate", "Ethyleneglycol", "Hexane", "HMPA", "Nitromethane", "Pentane",
					"Propanol", "Triethylamine", "Trifluoroacetic Acid"
					],
		lastSolventKey = "setSolvent/LastSolvent",
		lastSolvent = settings.value(lastSolventKey, solvents[0]),
		selNMRItems = [],
		selItems,
		i,
		s,
		diag,
		gbSolv,
		cbSolv;

	selItems = currentDocumentSelection();
	for (i = 0; i < selItems.length; ++i) {
		if (selItems[i].isValid() && selItems[i].name === "NMR Spectrum") {
			selNMRItems.push(new NMRSpectrum(selItems[i]));
		}
	}

	if (!selNMRItems.length) {
		MessageBox.critical(qsTr("There are no selected NMR spectra"));
		return;
	}

	diag = new Dialog(qsTr("Set Solvent"));
	gbSolv = new GroupBox();
	gbSolv.title = qsTr("Solvent Name:");
	cbSolv = new ComboBox();
	for (s = 0; s < solvents.length; ++s) {
		cbSolv.addItem(solvents[s]);
		if (solvents[s] === lastSolvent) {
			cbSolv.currentIndex = s;
		}
	}
	gbSolv.add(cbSolv);
	diag.add(gbSolv);

	if (diag.exec()) {
		if (cbSolv.currentIndex >= 0) {
			lastSolvent = solvents[cbSolv.currentIndex];
			settings.setValue(lastSolventKey, lastSolvent);
		}
		for (i = 0; i < selNMRItems.length; ++i) {
			selNMRItems[i].solvent = lastSolvent;
		}
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_SetSolvent = setSolvent;
}
